package com.ynding.cloud.common.model.util;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p> TODO  Dto，Vo，entity 转换工具类</p>
 *
 * @author ynding
 * @version 2021/5/12
 **/
public class BeanDtoVoUtils {

    /**
     * 实体类转换
     *
     * @return
     */
    public static <D, T> D toDtoBean(T source, Class<D> dClass) {
        if (source != null) {
            D d = null;
            try {
                d = dClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            BeanUtils.copyProperties(source, d);
            return d;
        }
        return null;
    }

    /**
     * 列表转换
     *
     * @return
     */
    public static <D, T> List<D> toDtoList(List<T> source, Class<D> dClass) {
        if (CollectionUtil.isNotEmpty(source)) {
            List<D> ds = source.stream().map(m -> {
                D d = null;
                try {
                    d = dClass.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                BeanUtils.copyProperties(m, d);
                return d;
            }).collect(Collectors.toList());
            return ds;
        }
        return null;
    }

}
